package com.example.tourpal.model;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class HttpUtils {
	private static String PATH = "http://bdfngdg:8080/myhttp/servlet/LoginAction"; // 鏈嶅姟绔湴鍧�
	private static URL url;

	public HttpUtils() {
		super();
	}

	// 闈欐�浠ｇ爜鍧楀疄渚嬪寲url
	static {
		try {
			url = new URL(PATH);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 鍙戦�娑堟伅浣撳埌鏈嶅姟绔�
	 * 
	 * @param params
	 * @param encode
	 * @return
	 */
	public static String sendPostMessage(Map<String, String> params,
			String encode) {
		StringBuilder stringBuilder = new StringBuilder();
		if (params != null && !params.isEmpty()) {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				try {
					stringBuilder
							.append(entry.getKey())
							.append("=")
							.append(URLEncoder.encode(entry.getValue(), encode))
							.append("&");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			stringBuilder.deleteCharAt(stringBuilder.length() - 1);
			try {
				HttpURLConnection urlConnection = (HttpURLConnection) url
						.openConnection();
				urlConnection.setConnectTimeout(3000);
				urlConnection.setRequestMethod("POST"); // 浠ost璇锋眰鏂瑰紡鎻愪氦
				urlConnection.setDoInput(true); // 璇诲彇鏁版嵁
				urlConnection.setDoOutput(true); // 鍚戞湇鍔″櫒鍐欐暟鎹�
				// 鑾峰彇涓婁紶淇℃伅鐨勫ぇ灏忓拰闀垮害
				byte[] myData = stringBuilder.toString().getBytes();
				// 璁剧疆璇锋眰浣撶殑绫诲瀷鏄枃鏈被鍨�琛ㄧず褰撳墠鎻愪氦鐨勬槸鏂囨湰鏁版嵁
				urlConnection.setRequestProperty("Content-Type",
						"application/x-www-form-urlencoded");
				urlConnection.setRequestProperty("Content-Length",
						String.valueOf(myData.length));
				// 鑾峰緱杈撳嚭娴侊紝鍚戞湇鍔″櫒杈撳嚭鍐呭
				OutputStream outputStream = urlConnection.getOutputStream();
				// 鍐欏叆鏁版嵁
				outputStream.write(myData, 0, myData.length);
				outputStream.close();
				// 鑾峰緱鏈嶅姟鍣ㄥ搷搴旂粨鏋滃拰鐘舵�鐮�
				int responseCode = urlConnection.getResponseCode();
				if (responseCode == 200) {
					// 鍙栧洖鍝嶅簲鐨勭粨鏋�
					return changeInputStream(urlConnection.getInputStream(),
							encode);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return "";
	}

	/**
	 * 灏嗕竴涓緭鍏ユ祦杞崲鎴愭寚瀹氱紪鐮佺殑瀛楃涓�
	 * 
	 * @param inputStream
	 * @param encode
	 * @return
	 */
	private static String changeInputStream(InputStream inputStream,
			String encode) {

		// 鍐呭瓨娴�
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = null;
		if (inputStream != null) {
			try {
				while ((len = inputStream.read(data)) != -1) {
					byteArrayOutputStream.write(data, 0, len);
				}
				result = new String(byteArrayOutputStream.toByteArray(), encode);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 鍒╃敤HttpUrlConnection 浠庢寚瀹氱殑URL涓幏鍙栨暟缁�
	 * 
	 * @param urlPath
	 * @return
	 * @throws Exception
	 */
	public static String readParse(String urlPath) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		URL url = new URL(urlPath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		InputStream inStream = conn.getInputStream();
		while ((len = inStream.read(data)) != -1) {
			outStream.write(data, 0, len);
		}
		inStream.close();
		return new String(outStream.toByteArray());// 閫氳繃out.Stream.toByteArray鑾峰彇鍒板啓鐨勬暟鎹�
	}

	/**
	 * 鍒╃敤HttpClient
	 * 
	 * 璁块棶鏁版嵁搴撳苟杩斿洖JSON鏁版嵁瀛楃涓�
	 * 
	 * @param params
	 *            鍚戞湇鍔″櫒绔紶鐨勫弬鏁�
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String doPost(List<NameValuePair> params, String url)
			throws Exception {
		String result = null;
		// 鑾峰彇HttpClient瀵硅薄
		HttpClient httpClient = new DefaultHttpClient();
		// 鏂板缓HttpPost瀵硅薄
		HttpPost httpPost = new HttpPost(url);
		if (params != null) {
			// 璁剧疆瀛楃闆�
			HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
			// 璁剧疆鍙傛暟瀹炰綋
			httpPost.setEntity(entity);
		}

		/*
		 * // 杩炴帴瓒呮椂 httpClient.getParams().setParameter(
		 * CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); // 璇锋眰瓒呮椂
		 * httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
		 * 3000);
		 */
		// 鑾峰彇HttpResponse瀹炰緥
		HttpResponse httpResp = httpClient.execute(httpPost);
		// 鍒ゆ柇鏄璇锋眰鎴愬姛
		if (httpResp.getStatusLine().getStatusCode() == 200) {
			// 鑾峰彇杩斿洖鐨勬暟鎹�
			result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
		} else {
			Log.i("HttpPost", "HttpPost鏂瑰紡璇锋眰澶辫触");
		}

		return result;
	}

	/**
	 * 瑙ｆ瀽
	 * 
	 * @throws JSONException
	 */
	@SuppressWarnings("unused")
	private static ArrayList<HashMap<String, Object>> Analysis(String jsonStr)
			throws JSONException {
		/******************* 瑙ｆ瀽 ***********************/
		JSONArray jsonArray = null;
		// 鍒濆鍖杔ist鏁扮粍瀵硅薄
		ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
		jsonArray = new JSONArray(jsonStr);
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			// 鍒濆鍖杕ap鏁扮粍瀵硅薄
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("logo", jsonObject.getString("logo"));
			map.put("logoLunbo", jsonObject.getString("logoLunbo"));
			map.put("biaoTi", jsonObject.getString("biaoTi"));
			map.put("yuanJia", jsonObject.getString("yuanJia"));
			map.put("xianJia", jsonObject.getString("xianJia"));
			map.put("id", jsonObject.getInt("id"));
			list.add(map);
		}
		return list;
	}

	/**
	 * 鑾峰彇缃戠粶鍥剧墖鐨勬暟鎹�
	 * 
	 * @param path
	 *            缃戠粶鍥剧墖璺緞
	 * @return
	 */
	public static Bitmap getImage(String path) throws Exception {

		/*
		 * URL url = new URL(imageUrl); HttpURLConnection conn =
		 * (HttpURLConnection) url.openConnection(); InputStream is =
		 * conn.getInputStream(); mBitmap = BitmapFactory.decodeStream(is);
		 */
		Bitmap bitmap = null;
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 鍩轰簬HTTP鍗忚杩炴帴瀵硅薄
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == 200) {
			InputStream inStream = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(inStream);
		}
		return bitmap;
	}

	/**
	 * 璇诲彇娴佷腑鐨勬暟鎹�浠巙rl鑾峰彇json鏁版嵁
	 * 
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] read(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}
	// public static void main(String[] args) {
	// Map<String, String> map = new HashMap<String, String>();
	// map.put("username", "admin");
	// map.put("password", "123456");
	// String result = sendPostMessage(map, "UTF-8");
	// System.out.println(">>>" + result);
	// }

}
